package net.kleinhenz.droidshop.system;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ObjectCache
{
	protected long CACHE_TTL = 10800000; // 3 hours
	
	protected Map<Query, Entry> cache = new HashMap<Query, Entry>();
	
	protected class Query 
	{
		public String keywords = null;
		public String locale = null;
		public Query(String keywords, String locale)
		{
			this.keywords = keywords;
			this.locale = locale;
		}
		@Override
		public boolean equals(Object obj)
		{
			if (obj==null || !(obj instanceof Query))
				return false;
			else 
				return ((((Query)obj).keywords==null && keywords==null) || ((Query)obj).keywords.equals(keywords))
						&& ((((Query)obj).locale==null && locale==null) || ((Query)obj).locale.equals(locale));
		}
		@Override
		public int hashCode()
		{
			return Arrays.hashCode(keywords.getBytes()) + Arrays.hashCode(locale.getBytes()); 
		}
	}
	
	protected class Entry
	{
		public Object object = null;
		public long timestamp = new Date().getTime();
		public Entry(Object object)
		{
			this.object = object;
		}
	}

	public Object getCache(String keywords, String locale)
	{
		Query query = new Query(keywords, locale);
		if (cache.containsKey(query) && cache.get(query).timestamp+CACHE_TTL<=new Date().getTime())
			cache.remove(query);
		if (cache.containsKey(query) && cache.get(query).timestamp+CACHE_TTL>new Date().getTime())
			return cache.get(query).object;
		
		return null;
	}

	public void putCache(String keywords, String locale, Object object)
	{
		Query query = new Query(keywords, locale);
		Entry entry = new Entry(object);
		cache.put(query, entry);
	}
}
